//
//  WFCustomizeCandidateMenuViewController.m
//  WeiFang
//
//  Created by WeiFang on 2023/10/14.
//  Copyright © 2023 WeiFang. All rights reserved.
//

#import "WFCustomizeCandidateMenuViewController.h"

#import "WFEatHeadCollectionViewCell.h"
#import "WFEatListCollectionViewCell.h"

#import "WFCustomizeCandidateMenuSearchView.h"

@interface WFCustomizeCandidateMenuViewController ()

@property (nonatomic,strong) WFCustomizeCandidateMenuSearchView *searchView;
@property (nonatomic,copy) NSString *keyword;
@property (nonatomic,copy) NSArray *dataAry;

@end

@implementation WFCustomizeCandidateMenuViewController

#pragma mark - 生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationItemTitleViewWithTitle:@"自定义候选菜单"];
    
    self.searchView.frame = CGRectMake(15,self.navigationBarHeight + 10, kScreenWidth - 15*2, 60);
    [self.view addSubview:self.searchView];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"WFEatHeadCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"WFEatHeadCollectionViewCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"WFEatListCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"WFEatListCollectionViewCell"];
        
    self.collectionView.frame = CGRectMake(0,self.searchView.frame.origin.y + self.searchView.frame.size.height + 20, kScreenWidth, kScreenHeight - (self.searchView.frame.origin.y + self.searchView.frame.size.height + 20) + 20);
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.layer.cornerRadius = 20;
    self.collectionView.layer.masksToBounds = YES;
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, -20, 0);
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    [self requestData];
}

- (void)requestData {
    NSArray *dataAry = [kDataManager getEatArray];
    self.dataAry = [NSMutableArray arrayWithArray:dataAry];
    [self refreshData];
}

#pragma mark - cellDataSource
    
- (NSArray *)cellDataSource {
    if (!self.dataSource) {
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:4];
        
        __block NSMutableArray *subarr = nil;
        __block NSDictionary *dict = nil;
  
        if (self.dataAry.count > 0) {

            subarr = [NSMutableArray arrayWithCapacity:1];
            
            dict =  @{@"class":WFEatHeadCollectionViewCell.class,
                      @"width":@(kScreenWidth),
                      @"height":@(40),
                      @"data":[WFEatHeadCollectionViewCellModel ittemModelWithTitle:@"候选菜单"],
                    @"delegate":@YES};
            [subarr addObject:dict];
            
            [self.dataAry enumerateObjectsUsingBlock:^(WFEatModel *ittem, NSUInteger idx, BOOL * _Nonnull stop) {
              
                CGSize titleSize = [ittem.food ex_sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(kScreenWidth, MAXFLOAT)];
                
                dict =  @{@"class":WFEatListCollectionViewCell.class,
                          @"width":@(titleSize.width + 54),
                          @"height":@(36),
                          @"data":[WFEatListCollectionViewCellModel ittemModelWithTitle:ittem.food index:idx],
                        @"delegate":@YES};
                [subarr addObject:dict];
            }];
                                    
            [arr addObject:subarr];
        }

        self.dataSource = arr;
    }
    return self.dataSource;
}

#pragma mark - UICollectionView 代理
    
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.cellDataSource.count;
}
    
//定义展示的UICollectionViewCell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSArray *arr = self.cellDataSource[section];
    return [arr count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *section = self.cellDataSource[indexPath.section];
    NSDictionary *cellDict = section[indexPath.row];
    
    Class classs = cellDict[@"class"];
    
    BaseCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(classs) forIndexPath:indexPath];
    
    NSNumber *delFlag = cellDict[@"delegate"];
    
    id delegate = nil;
    
    if (delFlag && delFlag.boolValue) {
        delegate = self;
    }
    
    [cell setData:cellDict delegate:delegate];
    
    return cell;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *section = self.cellDataSource[indexPath.section];
    NSDictionary *cellDict = section[indexPath.row];
    float width = [cellDict[@"width"] floatValue];
    float height = [cellDict[@"height"] floatValue];
    return CGSizeMake(width, height);
}
    
// 设置每个cell上下左右相距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

//设置最小行间距，也就是前一行与后一行的中间最小间隔
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}
    
// 设置最小列间距，也就是左行与右一行的中间最小间隔
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

#pragma mark WFCustomizeCandidateMenuSearchViewDelegate 输入框文本 添加

- (void)customizeCandidateMenuSearchView:(WFCustomizeCandidateMenuSearchView *)searchView buttonAction:(id)sender {
    if ([sender isKindOfClass:[UITextField class]]) {
        UITextField *textField = sender;
        _keyword = textField.text;
    } else if ([sender isKindOfClass:[UIButton class]]) {
        if (_keyword.length > 0) {
            //添加
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *date = [dateFormatter stringFromDate:[NSDate date]];
            
            WFEatModel *model = [WFEatModel new];
            model.food = _keyword;
            model.updateTime = date;
            [kDataManager addEatDataWithModel:model];
            [self showProgressHUD:@"添加成功"];
            self.searchView.myTextField.text = @"";
            [self requestData];
        } else {
            [self showProgressHUD:@"请输入菜单名称"];
        }
    }
}

#pragma mark WFEatListCollectionViewCellDelegate 删除

- (void)eatListCollectionViewCell:(WFEatListCollectionViewCell *)cell buttonAction:(UIButton *)sender {
    //删除
    WFEatModel *ittem = self.dataAry[cell.model.index];
    [kDataManager deleteEatDataDicWithEatId:ittem.eatId];
    [self requestData];
}

#pragma mark - refreshData
    
/**
 *  刷新tableView
 */
- (void)refreshData {
    self.dataSource = nil;
    [self.collectionView reloadData];
}

#pragma mark - NSNotification

//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification {
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;   //height 就是键盘的高度
    self.collectionView.frame = CGRectMake(0,self.searchView.frame.origin.y + self.searchView.frame.size.height + 20, kScreenWidth, kScreenHeight - (self.searchView.frame.origin.y + self.searchView.frame.size.height + 20) - height + 20);
}
 
//当键盘退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification {
    self.collectionView.frame = CGRectMake(0,self.searchView.frame.origin.y + self.searchView.frame.size.height + 20, kScreenWidth, kScreenHeight - (self.searchView.frame.origin.y + self.searchView.frame.size.height + 20) + 20);
}

#pragma mark - 懒加载

//搜索
- (WFCustomizeCandidateMenuSearchView *)searchView {
    if (!_searchView) {
        _searchView = [WFCustomizeCandidateMenuSearchView instanceView];
        [_searchView.myTextField becomeFirstResponder];
        [_searchView setData:[WFCustomizeCandidateMenuSearchViewModel ittemModelWithIsEdit:YES] delegate:self];
    }
    return _searchView;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end

